package de.fuberlin.dbs.wm.dao.util;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * The Database API.
 * Used to send querys to the database and resolves ResultSets or mapped Lists
 * 
 * 
 */
public class DatabaseTemplate {
	
	public <T> List<T> mapQuery(String sql, ResultMapper<T> mapper) throws SQLException {
		List<T> list = new ArrayList<T>();
		ResultSet rs = DatabaseSource.query(sql);
		while(rs.next()) {
			T t = mapper.mapResult(rs);
			if(t != null)
				list.add(t);
		}
		return list;
	}
	
	/**
	 * Fetch data from the table
	 * @param sql The SQL Query String
	 * @return A ResultSet object containing the result of the query
	 * @throws SQLException
	 */
	public ResultSet query(String sql) throws SQLException {
		return DatabaseSource.query(sql);
	}
	
	/**
	 * Method for UPDATE, INSERT or DELETE statements 
	 * @param sql A SQL-Query String
	 * @return either the row count for SQL Data Manipulation Language (DML) 
	 * 		statements or 0 for SQL statements that return nothing 
	 * @throws SQLException
	 */
	public int executeQuery(String sql) throws SQLException {
		return DatabaseSource.update(sql);
	}
}
